package com.im.util;

import com.im.redis.RedisPatternTopic;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil {
    /**
     * 保存连接 session 的地方
     */
    private static Map<String, WebSocketSession> SESSION = new ConcurrentHashMap<>();

    private static Map<String, List<String>> unreadMsg = new ConcurrentHashMap<>();
    /**
     * 存放未读消息
     */
    public static void readMsg(String id ,String content){
//        List<String> list = null == unreadMsg.get(id) ? new ArrayList<>() : unreadMsg.get(id);
//        list.add(content);
//        //放入未读消息
//        unreadMsg.put(id,list);
        List<String> o = RedisUtil.get("unreadMsg:" + id);
        if(null == o){
            o = new ArrayList<>();
        }
        o.add(content);
        RedisUtil.set("unreadMsg:" + id,o);
    }

    /**
     * 获取未读消息
     */
    public static List<String> getReadMsg(String id){
        List<String> o  = RedisUtil.get("unreadMsg:" + id);
        RedisUtil.delete("unreadMsg:" + id);
        return null == o ? new ArrayList<>() : o;
    }

    /**
     * 添加
     */
    public static void put(String id,WebSocketSession webSocketSession){
        SESSION.put(id, webSocketSession);
        RedisUtil.set(RedisPatternTopic.session + id,id);
    }

    /**
     * 删除
     */
    public static void remove(String id){
        if(null != id && !"".equals(id)){
            SESSION.remove(id);
            RedisUtil.delete(RedisPatternTopic.session + id);
        }
    }

    /**
     * 获取WebSocketSession
     */
    public static WebSocketSession get(String id){
        if(null ==id || "".equals(id)){
            return null;
        }
        return SESSION.get(id);
    }

    /**
     * 总条数
     */
    public static Integer size(){
        return RedisUtil.keys(RedisPatternTopic.session).size();
    }
}
